package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.domain.Address;
import com.itheima.reggie.mapper.AddressMapper;
import com.itheima.reggie.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


// 收货地址
@Service
@Transactional
public class AddressServiceImpl implements AddressService {
    @Autowired
    private AddressMapper addressMapper;
    // 地址列表
    @Override
    public List<Address> findList() {
        LambdaQueryWrapper<Address>qw=new LambdaQueryWrapper<>();
        qw.eq(Address::getUserId, UserHolder.get().getId());//用户ID
        //查询并返回

        return addressMapper.selectList(qw);
    }
// 新增地址

    @Override
    public void save(Address address) {
        address.setUserId(UserHolder.get().getId()); // 用户id
        address.setIsDefault(0);// 非默认地址
        // 2.mapper新增
        addressMapper.insert(address);


    }

    @Override
    public void setDefault(Long id) {
        // 1.把当前用户下所有收货地址设置为非默认
        // 1-1 设置修改内容
        Address address1 = new Address();
        address1.setIsDefault(0);
        //1-2 设置用户id为条件
        LambdaQueryWrapper<Address>qw=new LambdaQueryWrapper<>();
        qw.eq(Address::getUserId,UserHolder.get().getId());
        // 1-3 更新
        addressMapper.update(address1,qw);
        // 2.将当前收货地址设置为默认
        Address address2=new Address();
        address2.setId(id);// 收货地址id
        address2.setIsDefault(1); // 默认
        addressMapper.updateById(address2);
    }

    @Override
    public Address findDefault() {
        //1修改 条件
        LambdaQueryWrapper<Address>qw=new LambdaQueryWrapper<>();
        qw.eq(Address::getIsDefault,1); // 默认值 = 1
        qw.eq(Address::getUserId,UserHolder.get().getId());// 用户id

        return addressMapper.selectOne(qw);
    }
//删除
    @Override
    public void deleteIds(Long ids) {
   addressMapper.deleteById(ids);


    }
//回显
    @Override
    public Address findById(Long id) {
        Address address = addressMapper.selectById(id);
        LambdaQueryWrapper<Address>qw=new LambdaQueryWrapper<>();
        qw.eq(Address::getId,id);
        Address addresses = addressMapper.selectOne(qw);



        return address;
    }
    //    //修改
    @Override
    public void updateDefault(Address address) {
        address.setUserId(UserHolder.get().getId()); // 用户id
        address.setIsDefault(0);
        addressMapper.updateById(address);



    }


}
